<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
 */
//category function
function addNewCategory() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAddCategory'])) {
        $data = array();
        if($_POST['cat_title']=='') {
            $CONFIG["error_message"] .= "<li>Title can not be blank!</li>";
        }
        $data['cat_title'] = $_POST['cat_title'];
        $data['cat_parent'] = $_POST['cat_parent'];
        $data['cat_link'] = create_link($_POST['cat_title']);
        $data['cat_description'] = $_POST['cat_description'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['cat_active'] = $_POST['cat_active'];
        $data['user_id'] = $_SESSION["login"]["id"];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $db->exec_insert('cat_news', $data);
            $CONFIG["success_message"] = "<li>Add category success!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}

function editUpdateCategory() {
    global $db,$CONFIG;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        if(isset($_POST['submitFrmNewsAddCategory'])) {//update category
            $data = array();
            if($_POST['cat_title']=='') {
                $CONFIG["error_message"] .= "<li>Title can not be blank!</li>";
            }
            $data['cat_title'] = $_POST['cat_title'];
            $data['cat_parent'] = $_POST['cat_parent'];
            $data['cat_link'] = create_link($_POST['cat_title']);
            $data['cat_description'] = filter($_POST['cat_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['cat_active'] = filter($_POST['cat_active']);
            $data['user_id'] = $_SESSION["login"]["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('cat_news', $data, " cat_id=$cat_id ");
                $CONFIG["success_message"] = "<li>Update category success!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM cat_news WHERE cat_id=$cat_id");
    }
}

function deleteNewsCat() {
    global $db;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        $arrChildCatNews = getCatNewsIdToArray($cat_id,$trees=null);
        for($i=0;$i<count($arrChildCatNews);$i++) {
            if(intval($arrChildCatNews[$i])>0) {
                $db->exec_delete('cat_news',"cat_id=".$arrChildCatNews[$i]);
            }
        }
        $db->exec_delete('cat_news',"cat_id=$cat_id");
    }
}

function getCatNewsIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT cat_id FROM cat_news WHERE  cat_parent = ".intval($parent_id));
    if($rsCat) {
        while($rs = $db->fetch_array($rsCat)) {
            $trees[] = $rs['cat_id'];
            $trees = getCatNewsIdToArray($rs['cat_id'],$trees);
        }
    }
    return $trees;
}

function listAllNewsCategory($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_news WHERE  cat_parent = ".intval($parent_id)." ORDER BY cat_order,cat_id");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllNewsCategory($rs['cat_id'],$space.'----',$trees);
    }
    return $trees;
}

function multiActionCategoryNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_cat_id'];
        switch($_REQUEST['formNewsCategoryViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('cat_news','cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case "setStatusYes": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'yes'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case "setStatusNo": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'no'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}

//order category
function orderNewsCategory() {
    global $db,$CONFIG,$option;
    if(isset($_POST['submitFrmNewsOrder']) && $_POST['submitFrmNewsOrder']=="Submit") {//update
        $arrNewsCatID = $_POST['news_order'];
        if(count($arrNewsCatID)) {
            for($i=0;$i<count($arrNewsCatID);$i++) {
                if(intval($arrNewsCatID[$i])>0) {
                    $db->exec_update('cat_news',array("cat_order"=>$i),'cat_id='.intval($arrNewsCatID[$i]));
                }
            }
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL.get_string_url(array('action')));
            }else {
                return listAllNewsCategory();
            }
        }else {
            return listAllNewsCategory();
        }
    }else {//show
        return listAllNewsCategory();
    }

}
//end category function
//news
function addNewNews() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAdd'])) {
        $data = array();
        if($_POST['title']=='') {
            $CONFIG["error_message"] .= "<li>Title can not be blank!</li>";
        }
        if($_POST['description']=='') {
            $CONFIG["error_message"] .= "<li>Description can not be blank!</li>";
        }
        if($_POST['content']=='') {
            $CONFIG["error_message"] .= "<li>Content can not be blank!</li>";
        }
        $data['title'] = $_POST['title'];
        $data['title_link'] = create_link($_POST['title']);
        $data['cat_id'] = $_POST['cat_id'];
        $data['image'] = $_POST['image'];
        $data['description'] = $_POST['description'];
        $data['content'] = $_POST['content'];
        $data['type'] = $_POST['type'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['user_id'] = $_SESSION["login"]["id"];
        $tags = $_POST['keyword'];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $db->exec_insert('news', $data);
            $newsId = mysql_insert_id();

            //insert data to tags
            for($i=0;$i<count($tags);$i++) {
                if($tags[$i]!='') {
                    $tempTags = checkTagExist($tags[$i]);
                    if($tempTags=='donthave') {//chua ton` tai tag nay nen insert vao database
                        $tags_link = create_link($tags[$i]);
                        $db->query("INSERT INTO tags_news (tags, tags_link) VALUES ('$tags[$i]', '$tags_link')");
                        $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($newsId,".mysql_insert_id().")");
                    }else {//ton tai rui nen lay id (chinh la $tempTags)
                        $db->query("INSERT INTO news_relate_tags (news_id,tag_id) VALUES ($newsId,$tempTags)");
                    }
                }
            }
            if($_POST['submitType']=='exit') {
            //server_redirect(ADMIN_URL . '?module=news');
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
            $CONFIG["success_message"] = "<li>Add news success!</li>";
        }

    }
}

function checkTagExist($tag) {
    global $db;
    $rs = $db->query_first("SELECT id FROM tags_news WHERE tags='$tag'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function editUpdateNews() {
    global $db,$CONFIG;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        if(isset($_POST['submitFrmNewsAdd'])) {//update category
            $data = array();
            if($_POST['title']=='') {
                $CONFIG["error_message"] .= "<li>Title can not be blank!</li>";
            }
            if($_POST['description']=='') {
                $CONFIG["error_message"] .= "<li>Description can not be blank!</li>";
            }
            if($_POST['content']=='') {
                $CONFIG["error_message"] .= "<li>Content can not be blank!</li>";
            }
            $data['title'] = $_POST['title'];
            $data['title_link'] = create_link($_POST['title']);
            $data['cat_id'] = $_POST['cat_id'];
            $data['image'] = $_POST['image'];
            $data['description'] = $_POST['description'];
            $data['content'] = $_POST['content'];
            $data['type'] = $_POST['type'];
            //$data['create_date'] = date('Y-m-d H:i:s');
            $data['user_id'] = $_SESSION["login"]["id"];

            if($CONFIG["error_message"]=='') {
                $db->exec_update('news', $data, " id=$id ");
                $CONFIG["success_message"] = "<li>Update news success!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action','id')));
                }
            }
        }
        return $db->query_first("SELECT * FROM news WHERE id=$id");

    }else {
        server_redirect(SITE_URL . get_string_url(array('action','id')));
    }

}

function newsDetail() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        return $db->query_first("SELECT * FROM news WHERE id=$id");

    }else {
        $location = ADMIN_URL.'?module=news';
        redirect($location);
    }

}

function deleteNews() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        $db->exec_delete('news',"id=$id");
    }
}

function listAllNews() {
    global $db,$CONFIG;
    if(intval($_REQUEST['page'])>0) {
        $page = $_REQUEST['page'];
    }else {
        $page = 1;
    }
    // neu' bam vao nut tim kiem
    if($_REQUEST['submitFrmNewsSearch']=='Search') {
        if($_REQUEST['keyword']!='') {
            $searchCondition = ' AND (n.title LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.description LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.content LIKE \'%'.$_REQUEST['keyword'].'%\')';
        }
        if(intval($_REQUEST['cat_id'])>0) {
            $arrCatId = getCatNewsIdToArray($_REQUEST['cat_id']);
            array_push($arrCatId,$_REQUEST['cat_id']);
            if(count($arrCatId)>0) {
                $strCatId = implode(',', $arrCatId);
                $searchCondition .= " AND c.cat_id IN ($strCatId)";
            }else {
                $searchCondition .= " AND c.cat_id =".$_REQUEST['cat_id'];
            }
        }
        //echo $searchCondition;
        $rsNews = $db->query("SELECT n.id FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id WHERE 1 $searchCondition ORDER BY n.create_date DESC");
        $totalRows =  $db->num_rows($rsNews);
        $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
        $start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
        $limit = $CONFIG ['rows_per_page_news'];

        $rs = $db->query("SELECT n.id,n.cat_id,n.title,n.title_link,n.description,n.content,n.create_date,n.type,n.active,c.cat_title
                            FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id
                            WHERE 1 $searchCondition ORDER BY n.create_date DESC LIMIT $start,$limit");
        //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
        if($db->num_rows($rs)<1) {
            $page = $page - 1;
            if($page>1) {
                server_redirect(get_string_url()."&page=".$page);
            }

        }
        return array(
        "rs"=>$rs,
        "page"=>$page,
        "totalPages"=>$totalPages
        );
    }else {
        $rsNews = $db->query("SELECT n.id FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id WHERE 1 ORDER BY n.create_date DESC");
        $totalRows =  $db->num_rows($rsNews);
        $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
        $start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
        $limit = $CONFIG ['rows_per_page_news'];

        $rs = $db->query("SELECT n.id,n.cat_id,n.title,n.title_link,n.description,n.content,n.create_date,n.type,n.active,c.cat_title
                            FROM news n LEFT JOIN cat_news c ON n.cat_id = c.cat_id
                            WHERE 1 ORDER BY n.create_date DESC LIMIT $start,$limit");
        //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
        if($db->num_rows($rs)<1) {
            $page = $page - 1;
            if($page>1) {
                redirect(get_string_url()."&page=".$page);
            }

        }
        return array(
        "rs"=>$rs,
        "page"=>$page,
        "totalPages"=>$totalPages
        );
    }
}

function multiActionNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrNewsId = $_REQUEST['arr_news_id'];
        switch($_REQUEST['formNewsViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_delete('news','id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusYes": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'yes'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusPending": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'pending'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case "setStatusNo": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'no'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}
?>
